import { fileURLToPath, URL } from "node:url";
import { resolve } from "node:path";
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import dts from "vite-plugin-dts";
import { createSvgIconsPlugin } from "vite-plugin-svg-icons";
import VitePluginStyleInject from "./src/plugin/style-inject";

// https://vitejs.dev/config/
export default ({ command, mode }: { command: string; mode: string }) => {
  const plugins = [];
  if (mode === "development") {
    plugins.push(
      createSvgIconsPlugin({
        // 指定要缓存的图标文件夹
        iconDirs: [resolve(process.cwd(), "src/icons/svg")],
        // 执行icon name的格式
        symbolId: "icon-[dir]-[name]",
      })
    );
  }

  return defineConfig({
    build: {
      sourcemap: mode === "development" || "hidden",
      lib: {
        entry: resolve(__dirname, "src/svg-icon/index.ts"),
        name: "SvgIcon",
        fileName: "index",
      },
      rollupOptions: {
        // 确保外部化处理那些你不想打包进库的依赖
        external: ["vue"],
        output: {
          // 在 UMD 构建模式下为这些外部化的依赖提供一个全局变量
          globals: {
            vue: "Vue",
          },
        },
      },
      outDir: "lib",
    },
    plugins: [
      vue(),
      dts({
        entryRoot: "src/svg-icon",
        outputDir: "lib/types",
        tsConfigFilePath: "./tsconfig.json",
        cleanVueFileName: true,
      }),
      VitePluginStyleInject("injectStyle"),
      ...plugins,
    ],
    resolve: {
      alias: {
        "@": fileURLToPath(new URL("./src", import.meta.url)),
        mock: fileURLToPath(new URL("./mock", import.meta.url)),
      },
    },
    server: {
      host: true,
      proxy: {
        "/iconify": {
          target: "http://api.simplesvg.com/", // 图标服务
          rewrite: (path) => path.replace(/^\/iconify/, ""),
        },
      },
    },
  });
};
